"""
@FILE_NAME : robot_plugins
-*- coding : utf-8 -*-
@Author : Zhaokugua
@Time : 2022/10/8 22:42
"""
import requests
import jieba
import json
from PIL import Image
import re
import os
import math
import datetime
from urllib.parse import urlencode
import psutil
from app.pytyut import Pytyut
from app.views import cq_http_link

jieba.add_word("萝莉")  # 为啥jieba里面没有萝莉这个词啊！
jieba.add_word("菲谢尔")
jieba.add_word("原神")

Pytyut.node_link = 'https://jxgl20201105.tyutmate.cn/'
Pytyut.req_headers_add = {
    'User-Agent': 'Mozilla/5.0 (Linux; Android 11; Redmi K30 Pro Build/RKQ1.200826.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/86.0.4240.99 XWEB/3171 MMWEBSDK/20211001 Mobile Safari/537.36 MMWEBID/6338 MicroMessenger/8.0.16.2040(0x2800105D) Process/toolsmp WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64 miniProgram Edg/96.0.4664.110',
    'Sec-Fetch-Site': 'same-site',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-User': '?1',
    'Sec-Fetch-Dest': 'document',
    'Referer': 'https://helper.tyutmate.cn/tyut/index.html?random=fuckyo',
}
# 消息库，用来记录最近几条消息（记得在程序里写明自动清空）
# 记录消息库，便于批量撤回消息 #
# 列表里套列表类型[[qq号,消息id,群号], ...]
message_database = []

# 涩图索要库，记录近1分钟索要涩图的qq号和数目
setu_dict = {
    'time': -1,
}


# 自动广告禁言、踢人
# 根据关键词检测广告，检测到后立即执行撤回消息和禁言操作
# 并将相关聊天记录通知主人，并生成一键踢人链接
def auto_ban_ad(text):
    global message_database
    # 设置部分 #
    # 设置白名单群号
    group_id_list = ['1234546', '12345678', '123456789']
    # 设置机器人要通知的人的qq号
    master_qq_id = '123456'
    # 设置处理的关键词
    key_word = ['加大一新生墙', '都看下还是有没加的', '这不是广告哈', '都加下大一新生必备墙', '还有没加的同学', '（咨询）QQ', '大一新生必备资料墙QQ', '正规官方新生墙', '实名认证有偿',
                '十Q', '速度加一下', '做单子', '恋爱墙', '学校官方新生资料墙', '添加领取', '抓紧加下了', '墙墙QQ', 'qq:', 'qq：', 'QQ:', 'QQ：', 'QQ；',
                '墙墙qq', '信息交流互助群', '错过了重要通知', '18以下勿扰', '没加的抓紧加上']

    # 判断消息部分 #
    text_dict = json.loads(text)
    # 判断是否为管理群
    group_id = str(text_dict['group_id'])
    if group_id in group_id_list:
        pass
    else:
        return 'Not in group'
    # 将消息加入到消息数据库
    sender_qq_id = str(text_dict['user_id'])
    message_id = str(text_dict['message_id'])
    message_database.append([sender_qq_id, message_id, group_id])

    # 条数超过100条自动清空
    if len(message_database) > 100:
        message_database = []

    message = text_dict['message']
    # 判断是否为广告消息
    ad = False
    for item in key_word:
        # 判断出是广告
        if item in message:
            ad = True
            break
        else:
            pass
    if ad:
        pass
    else:
        return 'Safe'
    # 处理广告消息
    # 设置禁言
    ban_url = f'{cq_http_link}set_group_ban'
    params = {
        'group_id': group_id,
        'user_id': sender_qq_id,
    }
    requests.get(url=ban_url, params=params)
    # 撤回最近消息
    # 从数据库中筛选出这个人的近期消息id，并逐个撤回
    url = f'{cq_http_link}delete_msg'
    message_id_ban_list = []
    for message_item in message_database:
        if message_item[0] == sender_qq_id:
            message_id = message_item[1]
            message_id_ban_list.append(message_id)
            params = {
                'message_id': message_id
            }
            requests.get(url=url, params=params)
    # 通知管理员
    info_text1 = f'尊敬的管理员，您好。您管理的群({group_id})存在以下异常行为：'
    for item in message_id_ban_list:
        res_json = requests.get(f'{cq_http_link}/get_msg?message_id={item}').json()
        res_text = res_json['data']['sender']['nickname'] + '(' + str(res_json['data']['sender']['user_id']) + '):\n' + \
                   res_json['data']['message'] + '(' + str(res_json['data']['message_id']) + ')'
        info_text1 = info_text1 + '\n\n' + res_text
    kick_off_link = f'{cq_http_link}/set_group_kick?group_id={group_id}&user_id={sender_qq_id}'
    info_text1 = info_text1 + '\n\n 点击下方链接进行一键踢人：\n' + kick_off_link

    send_master_url = f'{cq_http_link}/send_private_msg'

    params = {
        'user_id': master_qq_id,
        'message': info_text1,
    }
    res = requests.get(url=send_master_url, params=params)
    return 'OK'


# 自动生成国庆头像
def get_red_head(text):
    # 设置部分 #
    # 设置白名单群号
    group_id_list = ['12345688', '123456']
    # 设置处理的关键词
    key_word = '我要国庆头像'
    # 判断消息部分 #
    text_dict = json.loads(text, strict=False)
    # 判断是否为管理群
    group_id = str(text_dict['group_id'])
    if group_id in group_id_list:
        pass
    else:
        return 'Not in group'
    message = text_dict['message']
    if key_word in message:
        pass
    else:
        return 'OK'
    # 获取发送者的QQ
    sender_qq_id = text_dict['user_id']

    # 下载并保存头像
    url = f'https://q1.qlogo.cn/g?b=qq&nk={sender_qq_id}&s=5'

    head_photo = requests.get(url).content

    # 写入头像文件
    with open('./static/img/head.jpg', 'wb') as head_photo_file:
        head_photo_file.write(head_photo)

    # 打开头像文件
    im_head = Image.open('./static/img/head.jpg')
    im_head = im_head.convert('RGBA')
    # 删除头像文件
    os.remove('./static/img/head.jpg')
    # 打开国旗文件
    im_flag = Image.open('./static/img/flag.png')
    im_flag = im_flag.convert('RGBA')
    # 把国旗的图片大小调整为头像的大小
    im_flag = im_flag.resize(im_head.size)
    # 透明通道合成
    img = Image.alpha_composite(im_head, im_flag)
    # 保存图片
    img.save(f'./static/img/{sender_qq_id}.png')

    # 把存好的图片发回去
    message = f'[CQ:at,qq={sender_qq_id}]\n点击下方链接查看：\nhttp://127.0.0.1:8000/static/img/{sender_qq_id}.png'
    url = f'{cq_http_link}send_group_msg'
    params = {
        'group_id': group_id,
        'message': message
    }
    requests.get(url, params=params)
    return 'OK'


# 戳一戳hitokoto
def poke_hitokoto(text):
    # 获取用户id
    test_dict = json.loads(text)
    sender_id = test_dict['sender_id']
    res = requests.get('http://hitokoto.jijidown.com/v2/api/hitokoto').json()
    hitokoto = res['res'][0]['hitokoto']
    source = res['res'][0]['source']

    # 消息文本
    message = hitokoto + '\n          ———' + source

    # 发送消息
    params = {
        'user_id': sender_id,
        'message': message,
    }
    requests.get(f'{cq_http_link}send_msg', params=params)
    return 'OK'
    # print(request.body)
    # return HttpResponse(request.body)
    # global test_dict
    # if request.method == 'POST':
    # if request.META.get('REMOTE_ADDR') == '81.68.240.146':
    #    for key in request.GET:
    #        test_dict[key] = request.GET.get(key)
    #    for key2 in request.POST:
    #        test_dict[key2] = request.POST.get(key2)
    #    test_dict = request
    # return HttpResponse(str(test_dict))


# 文件大小转换单位
def convert_size(size_bytes):
    if size_bytes == 0:
        return "0B"
    size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
    i = int(math.floor(math.log(size_bytes, 1024)))
    p = math.pow(1024, i)
    s = round(size_bytes / p, 2)
    return "%s %s" % (s, size_name[i])


# 私聊闪照
def show_flash_image(text):
    # 判断消息部分 #
    text_dict = json.loads(text, strict=False)

    message = text_dict['message']
    if 'type=flash' in message:
        pass
    else:
        return 'Not Flash Image'
    message = message.replace(',type=flash', '')
    sender_id = text_dict['user_id']
    url = f'{cq_http_link}/send_msg'
    params = {
        'user_id': sender_id,
        'message': message
    }
    requests.get(url, params=params)
    return 'OK'


# 自动提醒闪照
def show_group_flash_image(text, mode=2):
    # 设置群白名单
    group_id_list = ['123456', '1234567']
    # 判断消息部分 #
    text_dict = json.loads(text, strict=False)
    # 判断是否为管理群
    group_id = str(text_dict['group_id'])
    if group_id in group_id_list:
        pass
    else:
        return 'Not in group'
    message = text_dict['message']
    if 'type=flash' in message:
        pass
    else:
        return 'Not Flash Image'

    if mode == 1:
        # 模式1，修改原message的flash参数并原样发出去
        message = message.replace(',type=flash', '')
    elif mode == 2:
        # 模式2，获取图片详细信息并返回文本
        start = message.find('file=') + 5
        end = message.find('.image]') + 6
        # 获取图片名file_name
        image_file_name = message[start:end]
        # print(image_file_name)
        # 获取图片信息
        get_image_info_url = f'{cq_http_link}get_image'
        params = {
            'file': image_file_name,
        }
        img_info_json = requests.get(get_image_info_url, params=params).json()
        if img_info_json['status'] == 'ok':
            pass
        else:
            print(str(img_info_json))
            print(image_file_name)
            return 'Get Image Info Failed'
        if text_dict['sender']['card']:
            sender_name = text_dict['sender']['card'] + f'({text_dict["user_id"]})'
        else:
            sender_name = text_dict['sender']['nickname'] + f'({text_dict["user_id"]})'
        img_data = img_info_json["data"]
        message = f'【发现闪照】\n' \
                  f'发送者：{sender_name}\n' \
                  f'文件名：\n{img_data["filename"]}\n' \
                  f'大小：{convert_size(img_data["size"])}\n' \
                  f'地址：\n{img_data["url"]}'
    elif mode == 3:
        # 模式3 返回信息文本和图片
        raw_message = message.replace(',type=flash', '')
        start = message.find('file=') + 5
        end = message.find('.image') + 6
        # 获取图片名file_name
        image_file_name = message[start:end]
        # print(image_file_name)
        # 获取图片信息
        get_image_info_url = f'{cq_http_link}get_image'
        params = {
            'file': image_file_name,
        }
        img_info_json = requests.get(get_image_info_url, params=params).json()
        if img_info_json['status'] == 'ok':
            pass
        else:
            print(image_file_name)
            print(str(img_info_json))
            return 'Get Image Info Failed'
        if text_dict['sender']['card']:
            sender_name = text_dict['sender']['card'] + f'({text_dict["user_id"]})'
        else:
            sender_name = text_dict['sender']['nickname'] + f'({text_dict["user_id"]})'
        img_data = img_info_json["data"]
        message = f'【发现闪照】\n' \
                  f'发送者：{sender_name}\n' \
                  f'文件名：\n{img_data["filename"]}\n' \
                  f'大小：{convert_size(img_data["size"])}\n' \
                  f'地址：\n{img_data["url"]}' + raw_message
    else:
        message = '方法不存在！'

    # print(message)
    url = f'{cq_http_link}send_group_msg'
    params = {
        'group_id': group_id,
        'message': message
    }
    requests.get(url, params=params)
    return 'OK'


# 获取随机涩图
def get_random_setu(text):
    # 设置部分 #
    # 设置白名单群号
    group_id_list = ['123456', '123456']
    r18_group_id_list = ['123454', '123459', '1234567']
    # 设置处理的关键词
    key_word = '我要嗷嗷'
    # 判断消息部分 #
    text_dict = json.loads(text, strict=False)
    # 判断是否为管理群
    if text_dict.get('message_type') == 'group':
        group_id = str(text_dict['group_id'])
        if group_id in group_id_list:
            pass
        else:
            return 'Not in group'

    message = text_dict['message']

    # 关键词限制
    kw = ['我要嗷嗷', '根本不够涩！', '我要涩图', 'cos嗷嗷']
    if message in kw or '涩图' in message:
        pass
    else:
        return 'OK'

    if key_word in message:
        # 接口维护
        # message = '[CQ:image,cache=0,file=https://api.iyk0.com/ecy/api.php]'
        message = '[CQ:image,cache=0,file=https://www.98qy.com/sjbz/api.php]'
        # photo_info = requests.get('https://api.lolicon.app/setu/v2?r18=0&size=regular').json()['data'][0]['urls']['regular']
        # message = f'[CQ:image,cache=1,file={photo_info}]'
    elif message == '我要涩图':
        message = '[CQ:image,cache=0,file=http://iw233.fgimax2.fgnwctvip.com/API/Ghs.php]'
    elif message == '根本不够涩！':
        if text_dict.get('message_type') == 'group':
            group_id = str(text_dict['group_id'])
            if group_id in r18_group_id_list:
                # 两个json涩图接口，一个墙了，另一个之前不会用
                # photo_info = requests.get('https://api.nyan.xyz/httpapi/sexphoto?num=1&r18=true').json()['data']['url'][0]
                photo_info = \
                requests.get('https://api.lolicon.app/setu/v2?r18=1&size=regular').json()['data'][0]['urls']['regular']
                message = f'[CQ:image,cache=1,file={photo_info}]'
            else:
                message = f'未开启此功能'
        else:
            photo_info = requests.get('https://api.lolicon.app/setu/v2?r18=1&size=regular').json()['data'][0]['urls'][
                'regular']
            message = f'[CQ:image,cache=1,file={photo_info}]'

        # 自己搭的php涩图接口
        # message = '[CQ:image,cache=0,file=http://zhaokugu:14Xgge4dL7@lt1-3-228regina.pulsedmedia.com/user-zhaokugu/api/index.php]'
    elif message == 'cos嗷嗷':
        message = '功能维护，不要期待(๑＞ڡ＜)☆'
        # 接口维护
        # message = f'[CQ:image,cache=0,file=https://api.iyk0.com/cos]'
    # 正则匹配搜图
    elif message[-2:] == '涩图':
        if text_dict.get('message_type') == 'group':
            group_id = str(text_dict['group_id'])
            if group_id not in r18_group_id_list:
                r18 = '1' if 'r18' in message.lower() else '0'
            else:
                r18 = '0'
                message = message.replace('R18-G', '').replace('R18G', '').replace('R-18G', '').replace('r-18g',
                                                                                                        '').replace(
                    'R-18', '').replace('r-18', '')
        else:
            r18 = '1' if 'r18' in message.lower() else '0'
        message = message.replace('r18', '').replace('R18', '')
        tag_text = re.findall("我要(.*?)的涩图", message)
        if tag_text:
            tag_text = tag_text[0]
        else:
            return 'OK'
        photo_info = requests.get(f'https://api.lolicon.app/setu/v2?r18={r18}&size=regular&tag={tag_text}')
        flag = 0
        if '[]' in photo_info.text:
            tag_list = list(jieba.cut(tag_text))
            tag_info = '&tag=' + '&tag='.join(tag_list)
            photo_info = requests.get(f'https://api.lolicon.app/setu/v2?r18={r18}&size=regular' + tag_info)
            if '[]' in photo_info.text:
                message = '标签不存在！请尝试减少标签数或使用其他关键词。\r\n包含的标签：' + ','.join(tag_list)
                flag = 1
        if flag == 0:
            photo_info = photo_info.json()['data'][0]
            pid = photo_info['pid']
            uid = photo_info['uid']
            title = photo_info['title']
            author = photo_info['author']
            photo_link = photo_info['urls']['regular']
            tag_info = ' '.join(photo_info['tags'])
            info_msg = f'\r\n{title}({pid})\r\n作者：{author}({uid})\r\n标签：{tag_info}'
            message = f'[CQ:image,cache=0,file={photo_link}]{info_msg}'
    else:
        return 'OK'

    # 涩图频率限制
    now = datetime.datetime.now()
    # 初始化数据
    global setu_dict
    user_id = str(text_dict['user_id'])
    if setu_dict['time'] == -1:
        setu_dict['time'] = now.hour * 60 + now.minute
    else:
        # 先判断整体频率
        if now.hour * 60 + now.minute - setu_dict['time'] == 0:
            # 判断该用户是否在记录里，没有就加上，有就判断是否超出限制，没超出就+1

            if user_id in setu_dict.keys():
                if setu_dict[user_id] < 1:
                    setu_dict[user_id] += 1
                else:
                    # 不可以涩涩！
                    url = f'{cq_http_link}send_msg'
                    if text_dict.get('message_type') == 'group':
                        params = {
                            'group_id': group_id,
                            'message': '涩涩频率太快啦！不可以涩涩！'
                        }
                    else:
                        params = {
                            'user_id': user_id,
                            'message': '涩涩频率太快啦！不可以涩涩！'
                        }
                    requests.get(url, params=params)
                    return 'OK'
            else:
                setu_dict[user_id] = 0
        else:
            # 重新初始化setu_dict
            setu_dict = {
                'time': -1,
            }

    # 把存好的图片发回去
    url = f'{cq_http_link}send_msg'
    if text_dict.get('message_type') == 'group':
        params = {
            'group_id': group_id,
            'message': message
        }
    else:
        params = {
            'user_id': user_id,
            'message': message
        }
    requests.get(url, params=params)

    return 'OK'


# 太理bot
def tyut_bot(text):
    # 判断消息部分 #
    text_dict = json.loads(text, strict=False)
    if 'tyut' in text_dict['message']:
        with open('./consumer/tyut_info.csv', 'r+') as csv_file:
            rows = csv_file.read().split('\n')
        tyut_info_dict = {}
        for row in rows:
            row = row.split(',')
            # qq号 学号 密码 姓名
            if len(row) == 4:
                tyut_info_dict[row[0]] = [row[1], row[2], row[3]]
    else:
        return 'Not tyut msg'
    sender_qq = str(text_dict['user_id'])
    msg = 'ok'
    if '登录' in text_dict['message']:
        # tyut登录 学号 密码
        info_list = text_dict['message'].replace('\r', '').split('\n')
        user = Pytyut(info_list[1], info_list[2])
        try:
            login_info = user.login(debug=False)
        except ConnectionError:
            login_info = {'msg': '登录失败', 'info': '服务器访问量过大，请稍后重试。'}
        if login_info['msg'] == '登录成功':
            real_name = login_info['info']
        else:
            real_name = ''
            if '解码失败' in login_info['info']:
                error_info = '服务器内部错误。请稍后重试'
            else:
                error_info = login_info['info']
        if real_name:
            msg = '登录成功：' + real_name + '\n为保障您的隐私安全，建议您撤回登录消息。'
            with open('./consumer/tyut_info.csv', 'a+') as csv_file:
                csv_file.write(','.join([sender_qq, info_list[1], info_list[2], real_name]) + '\n')
        else:
            msg = '登录失败！\n' + error_info
            print(info_list)
    elif text_dict['message'] == 'tyut成绩查询':
        if sender_qq in tyut_info_dict.keys():
            user = Pytyut(tyut_info_dict[sender_qq][0], tyut_info_dict[sender_qq][1])
            if not user.login():
                msg = '登录出错，请尝试重新登录。'
            else:
                scores = user.get_class_scores()
                if not scores:
                    msg = '获取信息失败，请稍后再试。'
                else:
                    xnxq1 = scores[0]['Xnxq']
                    i = 0
                    msg = xnxq1 + '\n'
                    while scores[i]['Xnxq'] == xnxq1:
                        msg = msg + scores[i]['Kcm'] + '\n成绩：' + scores[i]['Cj'] + '  学分：' + scores[i]['Xf'] + '\n\n'
                        i += 1
        else:
            msg = '请先发送”tyut帮助“查看登录方法。'
    elif text_dict['message'] == 'tyut考试安排':
        if sender_qq in tyut_info_dict.keys():
            user = Pytyut(tyut_info_dict[sender_qq][0], tyut_info_dict[sender_qq][1])
            if not user.login():
                msg = '登录出错，请尝试重新登录。'
            else:
                tests = user.get_test_info(xnxq='', bydesk=True)
                if not tests:
                    msg = '获取信息失败，请稍后再试。'
                else:
                    msg = '【考试安排】\n'
                    for test in tests:
                        msg = msg + '\n'.join(['【' + test[1] + '】', test[2], test[3]]) + '\n'

        else:
            msg = '请先发送”tyut帮助“查看登录方法。'
    elif text_dict['message'] == 'tyut帮助':
        msg = '''【帮助菜单】\n ①登录教务系统：\ntyut登录\n这里填学号\n这里填教务系统的密码\n\n ②查询本学期成绩：\ntyut成绩查询
        \n③查询考试安排：\ntyut考试安排'''
    else:
        msg = '命令不存在！查看命令请发送”tyut帮助“'

    params = {
        'user_id': sender_qq,
        'message': msg,
    }
    requests.get(f'{cq_http_link}send_msg', params=params)
    return 'OK'


# 原神私服状态查看
def game_server_info(text):
    # 判断消息部分 #
    text_dict = json.loads(text, strict=False)

    message = text_dict['message']

    if message == "服务器状态":
        pass
    else:
        return None
    json_info = requests.get('http://ys.jixiaob.cn:5250/get_sys_info').json()
    cpu_percent = json_info['cpu_percent']
    memory_info = json_info['memory_info']
    swap_memory_info = json_info['swap_memory_info']
    # cpu_percent = psutil.cpu_percent()
    # memory_info = psutil.virtual_memory().percent
    # swap_memory_info = psutil.swap_memory().percent
    try:
        server_info1 = requests.get("https://ys.jixiaob.cn/status/server", verify=False).json()
        server_info1 = f'服务器版本：{server_info1["status"]["version"]}\r\n' \
                       f'在线玩家数：{server_info1["status"]["playerCount"]}/{server_info1["status"]["maxPlayer"]}\r\n'
        # f'新账号UID：{server_info["status"]["TotalAccount"]}'
    except BaseException as e:
        server_info1 = "服务器异常\r\n\r\n" + str(e) + str(e.__traceback__)
    try:
        server_info2 = requests.get("https://ys2.jixiaob.cn/status/server", verify=False).json()
        server_info2 = f'服务器版本：{server_info2["status"]["version"]}\r\n' \
                       f'在线玩家数：{server_info2["status"]["playerCount"]}/{server_info2["status"]["maxPlayer"]}\r\n'
        # f'新账号UID：{server_info["status"]["TotalAccount"]}'
    except BaseException as e:
        server_info2 = "服务器异常\r\n\r\n" + str(e) + str(e.__traceback__)
    message = f"服务器状态：\r\n###########\r\nCPU占用：{cpu_percent}%\r\n内存占用：{memory_info}%\r\nSWAP占用：{swap_memory_info}%\r\n" + '正式服：\r\n' + server_info1 + '\r\n测试服：\r\n' + server_info2
    sender_id = text_dict['user_id']
    url = f'{cq_http_link}/send_msg'
    group_id = str(text_dict['group_id'])
    params = {
        'group_id': group_id,
        'message': message
    }
    requests.get(url, params=params)
    return '服务器信息获取成功'


def group_in_out_plugin(text):
    """
    入群退群提醒插件
    可以设置群号和对应的提示信息
    如果没有设置就用默认的
    :param message:
    :return:
    """
    text_dict = json.loads(text)
    notice_type = text_dict['notice_type']
    if notice_type == 'group_decrease' or notice_type == 'group_increase':
        pass
    else:
        return 'OK'
    user_id = text_dict['user_id']
    operator_id = text_dict['operator_id']
    sub_type = text_dict['sub_type']

    default_in = f'欢迎[CQ:at,qq={user_id}]加入群聊！'
    default_out = f'[CQ:at,qq={user_id}]离开了我们'
    group_id = text_dict['group_id']
    group_in_dict = {
        '1234567': None,
        '1212': None,
        '121212': f"""
[CQ:at,qq={user_id}]
【新人必看 自助答疑流程】
----------------------------
『登录失效问题已修复，请更新最新版』

①确认你的软件版本号为：1.233.0，否则请发送<更新>二字或者群文件下载最新版

②查看你的问题是否可在下方连接内解决↓
docs.qq.com/doc/DYUpEV2tSZWpwUmFY

③你确认自己已经完整读完上方链接文档中的内容，且问题依旧？那么请@任一管理员
        """
    }
    group_out_dict = {
        '121212': f'[CQ:at,qq={user_id}]被[CQ:at,qq=12121212]吓跑了',
        '1212121': None,
    }

    if notice_type == 'group_increase':
        if f'{group_id}' not in group_in_dict.keys():
            return 'inout Not in group'
        message = group_in_dict[f'{group_id}'] if group_in_dict[f'{group_id}'] else default_in
    elif notice_type == 'group_decrease':
        if f'{group_id}' not in group_out_dict.keys():
            return 'inout Not in group'
        message = group_out_dict[f'{group_id}'] if group_out_dict[f'{group_id}'] else default_out
    else:
        return notice_type
    # print('message', message)
    url = f'{cq_http_link}send_group_msg'
    params = {
        'group_id': group_id,
        'message': message
    }
    requests.get(url, params=params)
    return 'OK'


def logo_create(text):
    text_dict = json.loads(text)
    message = text_dict['message']
    group_id = text_dict['group_id']
    if ' ' in message and message[:2] in ['ph', 'yt', '50', 'do', 'go']:
        blank_index = message.index(" ")
        info_dict = {
            "type": message[:blank_index],
            "text": message[blank_index + 1:]
        }
        url = "http://ys.jixiaob.cn:5250/get_photo?" + urlencode(info_dict).replace(r"+", "%20")
    else:
        return 'OK'

    message = '打开链接查看：\r\n' + url
    url = f'{cq_http_link}send_group_msg'
    params = {
        'group_id': group_id,
        'message': message
    }
    requests.get(url, params=params)
    return 'OK'



